package ie.ucc.cs.anggao.finalproject.server.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.tidy.Tidy;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.HtmlParser;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF extends HttpServlet {

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//Proxy
		
		System.setProperty("https.proxyHost", "10.51.255.250");
		System.setProperty("https.proxyPort", "8080");
		System.setProperty("http.proxyHost", "10.51.255.250");
		System.setProperty("http.proxyPort", "8080");
		
		HttpSession session = request.getSession();

		response.setContentType("application/pdf"); // Code 1
		Document document = new Document(PageSize.A4, 36, 36, 36, 36);

		try {
			PdfWriter.getInstance(document, response.getOutputStream());

			String text = (String) session.getAttribute("Text");
			text = "<html><body>" + text + "</body></html>";
			text = clean(text);
			ByteArrayInputStream bais = new ByteArrayInputStream(text
					.getBytes());
			System.out.println("GENETATE " + text);
			HtmlParser.parse(document, bais);

		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public String clean(String input) {
		ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Tidy tidy = new Tidy();
		tidy.setXHTML(true);
		tidy.setDocType("strict");
		tidy.setMakeClean(true);
		tidy.setQuiet(false);
		tidy.setIndentContent(true);
		tidy.setSmartIndent(true);
		tidy.setIndentAttributes(true);
		tidy.setWord2000(true);
		tidy.parse(bais, baos);
		return baos.toString();
	}

}